package com.rivues.task.resource;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.rivu.tools.TempletTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.bean.TaskInfo;
import com.rivues.module.platform.web.model.AnalyzerReport;
import com.rivues.module.platform.web.model.AnalyzerReportModel;
import com.rivues.module.platform.web.model.Cube;
import com.rivues.module.platform.web.model.JobDetail;
import com.rivues.module.platform.web.model.QueryLog;
import com.rivues.module.platform.web.model.RivuSite;
import com.rivues.module.platform.web.model.SearchResultTemplet;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.RivuTools;
import com.rivues.util.data.ReportData;
import com.rivues.util.iface.report.R3Request;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.serialize.JSON;
import com.rivues.util.service.ServiceHelper;
import com.rivues.util.tools.ExportFile;
import com.rivues.util.tools.FileUtil;
import com.rivues.util.tools.RivuCSVUtil;
import com.rivues.util.tools.RivuExcelUtil;

public class ReportResource extends Resource {
	private final Logger log = LoggerFactory.getLogger(ReportResource.class); 
	private JobDetail job ;
	private PublishedReport report = null ;
	private TaskInfo taskInfo ;
	private boolean isExcute = false;
	
	/**
	 * 构造器
	 * @param job
	 */
	@SuppressWarnings("unchecked")
	public ReportResource(JobDetail job){
		this.job = job ;
		List<PublishedReport> publishedReportList = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(PublishedReport.class).add(Restrictions.eq("orgi", job.getOrgi())).add(Restrictions.eq("id", job.getTaskid()))) ;
		if(publishedReportList.size()>0){
			report = publishedReportList.get(0);
			taskInfo = JSON.parseObject(report.getReportcontent(), TaskInfo.class)  ;
		}
	}
	
	@Override
	public void begin() throws Exception {
		
	}

	@Override
	public void end(boolean clear) throws Exception {
		this.job.getReport().setPages(0) ;
	}

	@Override
	public JobDetail getJob() {
		return job;
	}
	
	
	private boolean isExsitInArray(String string,String[] array){
		boolean flag = false;
		
		for (String str : array) {
			if(string.equals(str)){
				flag = true;
			}
		}
		
		return flag;
	}

	@Override
	public void process(OutputTextFormat meta, JobDetail job) {
		try {
			if(taskInfo!=null
					&&taskInfo.getReportids()!=null && taskInfo.getReportids().length>0
					&&taskInfo.getRunTypes()!=null && taskInfo.getRunTypes().length>0
					&&taskInfo.getFormats()!=null && taskInfo.getFormats().length>0){
				AnalyzerReport analyzerReport = null;
				AnalyzerReportModel reportModel = null ;
				List<String> filepathlist = new ArrayList<String>();
				ReportData reportData=null;
				ExportFile exportFile = null ;
				FileOutputStream fops = null;
				File file = null;
				String reportViewData  = null;
				StringBuffer emailcontent = new StringBuffer(taskInfo.getEmailContent()).append("<br/><br/>");
				HashMap<String , Object> values = null;
				boolean flag = false;
				
				for (String reportid : taskInfo.getReportids()) {
					PublishedReport publish_report = (PublishedReport) RivuDataContext.getService().getIObjectByPK(PublishedReport.class, reportid) ;
					if(publish_report!=null){
						analyzerReport = publish_report.getReport() ;
						
						if(analyzerReport!=null && analyzerReport.getModel()!=null && analyzerReport.getModel().size()>0){
				    		for(AnalyzerReportModel model : analyzerReport.getModel()){
				    				reportModel = model ;
				    				break;
				    		}
				    	}
						
						if(reportModel!=null){
							
							//flag = isExsitInArray("cache", taskInfo.getFormats());
							//if(flag && report.isCache()){//执行缓存
								try {
									reportData = RivuTools.getReportData(analyzerReport , null , reportModel,1, 20);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							//}
							
							flag = isExsitInArray("excel", taskInfo.getFormats());
							if(flag){//执行Excel
								try {
									file = new File(RivuTools.getDefaultBackupFilePath(report.getOrgi())+"/excel/"+publish_report.getName());
									if(!file.exists()){
										file.mkdirs();
									}
									String excelfilepath = RivuTools.getDefaultBackupFilePath(report.getOrgi())+"/excel/"+publish_report.getName()+"/"+publish_report.getName()+"_"+RivuTools.dateToString(new Date(), "yyyy-MM-dd_HHmmss")+".xlsx";
									filepathlist.add(excelfilepath);
									file = new File(excelfilepath);
									if(!file.exists()){
										file.createNewFile();
									}
									fops = new FileOutputStream(file);
									exportFile = new RivuExcelUtil(reportModel, analyzerReport , fops);
									exportFile.setHeadTitle(reportModel.getName()!=null  && reportModel.getName().length()>0 ? reportModel.getName() : report.getName()) ;
									reportModel.setExport(exportFile) ;
									reportModel.setIsexport(true);
									if(reportData.getData()!=null&&reportData.getData().size()>0){
						    			
					    				if(RivuDataContext.DataBaseTYPEEnum.HIVE.toString().equals(reportModel.getDbType())){
					    					reportModel.getExport().setReportData(reportData);
											reportModel.getExport().createFile(false);
											
					    				}else{
					    					reportModel.getExport().setReportData(reportData);
											reportModel.getExport().createFile(true);
					    				}
										
						    			
						    		}
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}finally{
									reportModel.getExport().close();//把数据写出
									if(fops!=null){
										try {
											fops.close();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
							}
							
							flag = isExsitInArray("csv", taskInfo.getFormats());
							if(flag){//执行csv
								try {
									file = new File(RivuTools.getDefaultBackupFilePath(report.getOrgi())+"/csv/"+publish_report.getName());
									if(!file.exists()){
										file.mkdirs();
									}
									
									String csvfilepath = RivuTools.getDefaultBackupFilePath(report.getOrgi())+"/csv/"+publish_report.getName()+"/"+publish_report.getName()+"_"+RivuTools.dateToString(new Date(), "yyyy-MM-dd_HHmmss")+".csv";
									filepathlist.add(csvfilepath);
									file = new File(csvfilepath);
									if(!file.exists()){
										file.createNewFile();
									}
									fops = new FileOutputStream(file);
									exportFile = new RivuCSVUtil(reportModel, analyzerReport , fops);
									exportFile.setHeadTitle(reportModel.getName()!=null && reportModel.getName().length()>0 ? reportModel.getName() : report.getName()) ;
									reportModel.setExport(exportFile) ;
									reportModel.setIsexport(true);
									if(reportData.getData()!=null&&reportData.getData().size()>0){
						    			
					    				if(RivuDataContext.DataBaseTYPEEnum.HIVE.toString().equals(reportModel.getDbType())){
					    					reportModel.getExport().setReportData(reportData);
											reportModel.getExport().createFile(false);
											
					    				}else{
					    					reportModel.getExport().setReportData(reportData);
											reportModel.getExport().createFile(true);
					    				}
										
						    			
						    		}
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}finally{
									reportModel.getExport().close();//把数据写出
									if(fops!=null){
										try {
											fops.close();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
							}
							
							flag = isExsitInArray("html", taskInfo.getFormats());
							if(flag){//执行html
								try {
									file = new File(RivuTools.getDefaultBackupFilePath(report.getOrgi())+"/html/"+publish_report.getName());
									if(!file.exists()){
										file.mkdirs();
									}
									
									String csvfilepath = RivuTools.getDefaultBackupFilePath(report.getOrgi())+"/html/"+publish_report.getName()+"/"+publish_report.getName()+"_"+RivuTools.dateToString(new Date(), "yyyy-MM-dd_HHmmss")+".html";
									filepathlist.add(csvfilepath);
									file = new File(csvfilepath);
									if(!file.exists()){
										file.createNewFile();
									}
									fops = new FileOutputStream(file);
									
									values = new HashMap<String , Object>();
									values.put("report", analyzerReport) ;
									values.put("filters", analyzerReport.getFilters()) ;
									values.put("reportData",reportData ) ;
									values.put("reportModel", reportModel) ;
									
									reportViewData = TempletTools.getTemplet(
											(SearchResultTemplet) RivuDataContext.getService().getIObjectByPK(SearchResultTemplet.class, "402881e43ab07e65013ab080e4c65002"), values) ;
									emailcontent.append(publish_report.getName());
									if("appendix".equals(taskInfo.getEmailType())){
										emailcontent.append(reportViewData);
										emailcontent.append("<br/><br/>");
									}
									fops.write(reportViewData.getBytes("UTF-8"));
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}finally{
									reportModel.getExport().close();//把数据写出
									if(fops!=null){
										try {
											fops.close();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
							}
							
							
						}
						
					}
				}
				
				flag = isExsitInArray("email", taskInfo.getRunTypes());
				if(flag){//发送邮件
					values = new HashMap<String , Object>();
					if(analyzerReport.getModel()!=null && analyzerReport.getModel().size()>0){
						values.put("report", this.report) ;
						values.put("filters", analyzerReport.getFilters()) ;
						try {
							RivuTools.sendMail(this.taskInfo.getEmails(), null, taskInfo.getEmailTitle(),emailcontent.toString() , filepathlist);
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				}
				
				flag = isExsitInArray("save", taskInfo.getRunTypes());
				
				if(!flag){//执行保存
					try {
						for (String string : filepathlist) {
							if(string!=null){
								FileUtil.deleteFile(string);
							}
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				

			}else{
				System.out.println("任务已执行，但是配置错误，没有做任何操作！");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			this.isExcute = true;
		}
		
	}

	@Override
	public OutputTextFormat next() throws Exception {
		OutputTextFormat outTextFormat = null ;
		if(!this.isExcute){
			outTextFormat = new OutputTextFormat(job) ;
		}
		return outTextFormat;
	}

	@Override
	public boolean isAvailable() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public OutputTextFormat getText(OutputTextFormat object) throws Exception {
		return object;
	}

	@Override
	public void rmResource() {
		if(this.report!=null){
			RivuDataContext.getService().deleteIObject(report) ;
		}
	}

	@Override
	public void updateTask() {
		
	}


}
